#!/bin/bash

# 数据库配置
DB_HOST="182.92.71.132"
DB_PORT="13306"
DB_USER="root"
DB_PASS="cfCNxfeea536AttJ"
DB_NAME="zct-prod-2025-06-21"
# 多个 COMPANY_ID 值，用逗号分隔
COMPANY_IDS=("2" "山西榆次北山煤业有限公司")
EXPORT_FILE="zct-prod.sql"

# 删除已存在的导出文件
if [ -f "$EXPORT_FILE" ]; then
    echo "发现已存在的导出文件，正在删除..."
    rm -f "$EXPORT_FILE"
    echo "旧文件已删除"
fi

# 获取所有表名
TABLES=$(mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -N -e "SHOW TABLES FROM \`$DB_NAME\`;")

# 开始导出
echo "开始导出数据库: $DB_NAME"
echo "----------------------------------------"

for TABLE in $TABLES; do
    # 检查表是否有 company_id 字段
    HAS_COMPANY_ID=$(mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -N -e "
        SELECT COUNT(*) FROM information_schema.columns
        WHERE table_schema = '$DB_NAME'
        AND table_name = '$TABLE'
        AND column_name = 'company_id';
    ")

    # 构建导出命令
    if [ "$HAS_COMPANY_ID" -gt 0 ]; then
        # 构建 WHERE 条件，匹配多个 COMPANY_ID
        WHERE_CLAUSE="company_id IN ("
        for ID in "${COMPANY_IDS[@]}"; do
            WHERE_CLAUSE+="'$ID',"
        done
        WHERE_CLAUSE=${WHERE_CLAUSE%,}")"  # 移除最后一个逗号并闭合括号
        
        echo "导出表: $TABLE (带条件 $WHERE_CLAUSE)"
        mysqldump -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" \
            --where="$WHERE_CLAUSE" \
            "$DB_NAME" "$TABLE" >> "$EXPORT_FILE"
    else
        echo "导出表: $TABLE (无条件)"
        mysqldump -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" \
            "$DB_NAME" "$TABLE" >> "$EXPORT_FILE"
    fi

    # 添加表分隔注释
    echo "-- ----------------------------------------" >> "$EXPORT_FILE"
    echo "-- 表 $TABLE 导出结束" >> "$EXPORT_FILE"
    echo "-- ----------------------------------------" >> "$EXPORT_FILE"
    echo "" >> "$EXPORT_FILE"
done

echo "----------------------------------------"
echo "导出完成! 文件保存在: $EXPORT_FILE"
echo "总大小: $(du -sh "$EXPORT_FILE" | cut -f1)"